<?php
/**
 * 
 * Enter description here ...
 * @author apple
 *
 */

class Stock_mdl extends CI_Model
{
	
		const TB_STOCK = 'cj_stock';
	
	public function __construct()
	{
		parent::__construct();
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $page
	 * @param unknown_type $limit
	 * @param unknown_type $offset
	 * @param unknown_type $order
	 * @param unknown_type $ptype
	 */
	public function get_stock_list($page = true,$limit = 0, $offset = 0, $order = 'DESC',$ptype = 0)
	{
		if($page){
			$this->db->limit(intval($limit));
			$this->db->offset(intval($offset));
			return $this->db->get(self::TB_STOCK)->result_array();
		}
		else {
			$reward = array();
			$reward = $this->db->get(self::TB_STOCK)->result_array();
			return $reward;
		}

	}
	
	/**
	 * 
	 */
	
	public function getStockhaved()
	{
		$stock = array();
		$tmp = array();
		$stock = $this->db->select('stock.id,stock.cardnum,stock.rewardid,product.productname,product.ptype')
				->from('cj_stock as stock')
				->join('cj_products as product', 'stock.productid = product.id')
				->where('stock.rewardid > ' ,0)
				->get()
				->result_array();
		if ( !empty( $stock ) ) {
			
			foreach( $stock as $key =>$value){
				$tmp[$value['rewardid']][] = $value;
			}
		}
		return $tmp;
	}
	
	/**
	 * 
	 * 
	 * @param array $data
	 */
	public function _addStock($data)
	{	
		return $this->db->insert(self::TB_STOCK,$data);
	}
	
	/**
	 * 
	 * ...
	 * @param int $id
	 */
	public function _delStock($id)
	{
		$this->db->delete(self::TB_STOCK, array('id' => $id)); 
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}
	
	/**
	 * 随机取一个还没被使用的奖品
	 */
	
	public function getStockByOne($productid,$data,$config)
	{

		return $this->db->limit(1)
				->update(self::TB_STOCK, $data, $config);

	}
	
	/**
	 * 取得活动的奖品
	 */
	public function getStockByRewardid($rewardid)
	{
		$stock = array();
		$stock = $this->db->select('stock.id,stock.productid')
				->where('stock.rewardid',$rewardid)
				->from('cj_stock as stock')
				->get()
				->result_array();
		return $stock;
		
	}
	
	/**
	 * 去掉奖品属性
	 */
	
	public function setStockNum($config,$data)
	{
		return $this->db->update(self::TB_STOCK, $data, $config);
				
	}
	
	
}